package com.tangdi.mkfile.gzdwmx;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.tangdi.Utils;
import com.tangdi.Bean.CZGZ_DWCOUNT;
import com.tangdi.Bean.CZGZ_GZLB;
import com.tangdi.Bean.CZGZ_SJGZ;
import com.tangdi.Bean.CZGZ_ZGGZMX;
import com.tangdi.Bean.XM_BM_XM_MC;
import com.tangdi.Dao.impl.GongziMXImpl;

public class CreateDWGZMXPDF_TOTAL {
	private Logger logger = Logger.getLogger(CreateDWGZMXPDF_TOTAL.class);
	String pdf_url_root = Utils.getFilePath("root_path");
	private String folder_Name = "工资发放明细表_ALL";
	private String file_Type = "pdf";
	private Font FontChinese;
	public int createPDF(Map<String,List<XM_BM_XM_MC>> map_bm_mc_list,List<CZGZ_DWCOUNT> listDWCOUNT,List<CZGZ_GZLB> list_gz_lb,String month) {
		StringBuffer sql_select = null;
		StringBuffer sql_select_mx = null;
		String sql_select_lb_count = null;
		String sql_select_lb_mx = null;
		int initSize = 0;
		float width = 30f;
		String pdf_url = pdf_url_root + "/" + month + "/" + file_Type + "/" + folder_Name + "/" + month + "_工资明细_ALL.pdf";
		
		
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    try {
	        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
	        //BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
	        FontChinese = new Font(bfChinese, 7, Font.NORMAL);
	        Document document = new Document(new RectangleReadOnly(700F, 791F),0,0,0,0);
	        File file = new File(pdf_url);
			if(!file.exists()){
			    //先得到文件的上级目录，并创建上级目录，在创建文件
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
	        PdfWriter.getInstance(document, new FileOutputStream(pdf_url));
	 
			PdfWriter.getInstance(document, baos); 
			document.open(); 
			
			PdfPTable table = null;
			GongziMXImpl gzmx = new GongziMXImpl();
			for(int i = 0; i < listDWCOUNT.size(); i++){
				String gz_lb = listDWCOUNT.get(i).getGZ_LB_DM();
				String gz_dw_dm = listDWCOUNT.get(i).getDW_DM();
				String gz_dw_mc = listDWCOUNT.get(i).getDW_MC();
				
				if(i != 0){//单位名称不同 或 单位名称相同工资类别不同 均新起一页
					if(listDWCOUNT.get(i).getDW_DM().equals(listDWCOUNT.get(i-1).getDW_DM())){
						if(!listDWCOUNT.get(i).getGZ_LB_DM().equals(listDWCOUNT.get(i-1).getGZ_LB_DM())){
							document.newPage();
						}
					}else{
						document.newPage();
					}
				}
				//查找不全为空值的列，为空的列舍弃，只保留不为空的列 start
				sql_select = new StringBuffer("SELECT ");
				List<XM_BM_XM_MC> list_BM_MC = map_bm_mc_list.get(listDWCOUNT.get(i).getGZ_LB_DM());
				List<XM_BM_XM_MC> list_BM_MC_temp =  new ArrayList<XM_BM_XM_MC>();
				
				logger.info(" 单位名称："+gz_dw_mc + " |  单位代码："+gz_dw_dm + "  工资类别：" + gz_lb + " 科目数量： " +list_BM_MC.size());
				for(int m = 0; m < list_BM_MC.size(); m++){
					//sql_select.append("NVL(SUM("+ list_BM_MC.get(m).getXM_BM() +"),'0') AS " +list_BM_MC.get(m).getXM_BM() + ",");
					sql_select.append("IFNULL(to_number(SUM("+ list_BM_MC.get(m).getXM_BM() +")),'0') AS " +list_BM_MC.get(m).getXM_BM() + ",");
					
				}
				sql_select_lb_count = sql_select.substring(0, sql_select.length() - 1);

				//按工资类别、单位代码，汇总工资明细各科目的值
				CZGZ_ZGGZMX gzDW_Count = new CZGZ_ZGGZMX();
				gzDW_Count = gzmx.getCountGZByLB_DW(month, gz_dw_dm, gz_lb, list_BM_MC, sql_select_lb_count);
				
				//赋值list_BM_MC_temp 去除为空的列
				Iterator<XM_BM_XM_MC> it_bm_mc = list_BM_MC.iterator();
				while(it_bm_mc.hasNext()){
					XM_BM_XM_MC bm_mc = it_bm_mc.next();
					String value_temp = (String)Utils.getFieldReflect(gzDW_Count,CZGZ_ZGGZMX.class,bm_mc.getXM_BM());
					if(!((value_temp.trim()).equals("0.00") || (value_temp.trim()).equals("0"))){
						list_BM_MC_temp.add(bm_mc);
					}
				}
				
				//查找不全为空值的列，为空的列舍弃，只保留不为空的列 end				
				
				//根据有值的列查明细
				initSize = list_BM_MC_temp.size();
				initSize = initSize + 2;
				
				sql_select_mx = new StringBuffer("SELECT TRIM(YF) AS YF, TRIM(NME) AS NME, ");
				for(int m = 0; m < list_BM_MC_temp.size(); m++){
					sql_select_mx.append("TRIM("+ list_BM_MC_temp.get(m).getXM_BM() +") AS " +list_BM_MC_temp.get(m).getXM_BM() + ",");
				}
				sql_select_lb_mx = sql_select_mx.substring(0, sql_select_mx.length() - 1);
				
				float[] cellWidths = new float[initSize];
				for(int a = 0; a < initSize; a++){
					cellWidths[a] = width;
			    }
				cellWidths[0] = 15f;
				cellWidths[initSize -1] = 40f;
								
				table = new PdfPTable(cellWidths);
				//***************表连续不分页，至关重要的作用 
				//table.setKeepTogether(true);
				
				table.setTotalWidth(initSize * width);
				//table.setSpacingBefore(3f);
				//table.getDefaultCell().setMinimumHeight(35);
				//工资明细list
				List<CZGZ_ZGGZMX> listmx=new ArrayList<CZGZ_ZGGZMX>();
				
				listmx = gzmx.listGZMXReportByLB(month, gz_dw_dm, gz_lb,list_BM_MC_temp, sql_select_lb_mx);
				table.addCell(getCell_noBorder("工    资    发    放    明    细    表",initSize,1, Element.ALIGN_CENTER, Element.ALIGN_BOTTOM,new Font(bfChinese, 15, Font.UNDERLINE)));
				//表头
				table.addCell(getCell_noBorder("单位名称：" + gz_dw_mc, (int)Math.ceil(initSize / 2), 1, Element.ALIGN_LEFT, Element.ALIGN_BOTTOM,FontChinese));
				table.addCell(getCell_noBorder(month.substring(0, 4) + "年" + month.substring(4, 6)+ "月", (initSize - (int)Math.ceil(initSize / 2)), 1, Element.ALIGN_RIGHT, Element.ALIGN_BOTTOM,FontChinese));
				//列名--start
				table.addCell(getCell("序号",1,1, Element.ALIGN_CENTER, Element.ALIGN_BOTTOM,FontChinese));
				table.addCell(getCell("姓名",1,1, Element.ALIGN_CENTER, Element.ALIGN_BOTTOM,FontChinese));
				for(int h = 0; h < list_BM_MC_temp.size(); h++){//显示工资科目名称
					table.addCell(getCell(list_BM_MC_temp.get(h).getXM_MC(),1,1, Element.ALIGN_CENTER, Element.ALIGN_BOTTOM,FontChinese));
					}
				//列名--end
				
				for(int j = 0; j < listmx.size(); j++){

					CZGZ_ZGGZMX gz_mx = listmx.get(j);
										
	                //列值 --start
					table.addCell(getCell(String.valueOf(j + 1),1,1, Element.ALIGN_CENTER, Element.ALIGN_BOTTOM,FontChinese));
					table.addCell(getCell(gz_mx.getNME(),1,1, Element.ALIGN_LEFT, Element.ALIGN_BOTTOM,FontChinese));
					for(int k = 0; k < list_BM_MC_temp.size(); k++){//根据工资类别反射查找工资科目
						String gz_value = (String)Utils.getFieldReflect(gz_mx,CZGZ_ZGGZMX.class,list_BM_MC_temp.get(k).getXM_BM());
						table.addCell(getCell((((gz_value.trim()).equals("0") || (gz_value.trim()).equals("0.00"))  ? " " : (gz_value.trim())), 1, 1, Element.ALIGN_RIGHT, Element.ALIGN_BOTTOM,FontChinese));
						}
					//列值 --end
					}
				//单位合计 start
				table.addCell(getCell(String.valueOf(listmx.size() + 1), 1, 2, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE,FontChinese ));
				table.addCell(getCell("合 计", 1, 2, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE,FontChinese));
				for(int k = 0; k < list_BM_MC_temp.size(); k= k+2){//汇总各科目金额 up
					String gz_value = (String)Utils.getFieldReflect(gzDW_Count,CZGZ_ZGGZMX.class,list_BM_MC_temp.get(k).getXM_BM());
					table.addCell(getCell((((gz_value.trim()).equals("0") || (gz_value.trim()).equals("0.00"))  ? " " : (gz_value.trim())), 2, 1, Element.ALIGN_LEFT, Element.ALIGN_BOTTOM,FontChinese));
					}
				for(int k = 1; k < list_BM_MC_temp.size();  k= k+2){//汇总各科目金额 down
					String gz_value = (String)Utils.getFieldReflect(gzDW_Count,CZGZ_ZGGZMX.class,list_BM_MC_temp.get(k).getXM_BM());
					table.addCell(getCell((((gz_value.trim()).equals("0") || (gz_value.trim()).equals("0.00"))  ? " " : (gz_value.trim())), 2, 1, Element.ALIGN_RIGHT, Element.ALIGN_BOTTOM,FontChinese));
					}
				if(list_BM_MC_temp.size() % 2 != 0){//如果为奇数 补上最后cell
					table.addCell(getCell("", 1, 1, Element.ALIGN_RIGHT, Element.ALIGN_BOTTOM,FontChinese));
				}
				//单位合计 end
				table.addCell(getCell_noBorder(" ", initSize, 1, Element.ALIGN_CENTER, Element.ALIGN_BOTTOM,FontChinese));
				
				table.addCell(getCell_noBorder("银行付讫（盖章）：", (int)Math.ceil(initSize / 2), 1, Element.ALIGN_LEFT, Element.ALIGN_BOTTOM,FontChinese));
				table.addCell(getCell_noBorder("制表人：", (initSize - (int)Math.ceil(initSize / 2)), 1, Element.ALIGN_LEFT, Element.ALIGN_BOTTOM,FontChinese));
				
				// 设置表格宽度
				if(initSize >= 15){
					table.setWidthPercentage(99); 
				}else{
					table.setWidthPercentage(99 * (initSize / (float)15)); 
				}
				
		    	document.add(table);
				}
			 
	    	document.close();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	return -1;
		}
	    return 0;
	}

	private PdfPCell getCell_noBorder(String cellValue, int colspan, int rowSpan, int x_position, int y_position, Font font) {
	    PdfPCell cell = new PdfPCell();
	    try {
	        cell = new PdfPCell(new Phrase(cellValue, font));
	        cell.setRowspan(rowSpan);
	        cell.setColspan(colspan);
	        //cell.setFixedHeight(36.547f);
	        cell.setBorder(0);
	        cell.setHorizontalAlignment(x_position);
	        cell.setVerticalAlignment(y_position);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return cell;
	}
	
	private PdfPCell getCell(String cellValue, int colspan, int rowSpan, int x_position, int y_position, Font font) {
	    PdfPCell cell = new PdfPCell();
	    try {
	        cell = new PdfPCell(new Phrase(cellValue, font));
	        cell.setRowspan(rowSpan);
	        cell.setColspan(colspan);
	        //cell.setFixedHeight(36.547f);
	        //cell.setBorder(0);
	        cell.setHorizontalAlignment(x_position);
	        cell.setVerticalAlignment(y_position);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return cell;
	}
	public static void main(String[] args) {
		//年月
		String month = "201905";
		List<CZGZ_DWCOUNT> listDWCOUNT=new ArrayList<CZGZ_DWCOUNT>();
		GongziMXImpl gz_dw_count = new GongziMXImpl();
		listDWCOUNT = gz_dw_count.listGZDWCount(month);
		
		//工资类别，科目项信息
		Map<String,List<XM_BM_XM_MC>> map_bm_mc_list = new HashMap<String,List<XM_BM_XM_MC>>();
		//工资明细list
		List<CZGZ_ZGGZMX> listmx=new ArrayList<CZGZ_ZGGZMX>();
		//工资类别list
		List<CZGZ_GZLB> listlb=new ArrayList<CZGZ_GZLB>();
		GongziMXImpl gzlb = new GongziMXImpl();
		listlb = gzlb.listGZLBReport(month);
		//实际工资科目 按工资类别
		List<CZGZ_SJGZ> list_sjgz=new ArrayList<CZGZ_SJGZ>();
		GongziMXImpl sjgz = new GongziMXImpl();
		list_sjgz = sjgz.listSJGZReport(month);
		
		System.out.println("listmx:" + listmx.size() + "  listlb:" + listlb.size() + "   list_sjgz:" + list_sjgz.size());
		//组装工资类别 ，实际工资科目项，对应好关系；方便后续使用
		for(int i=0;i<listlb.size();i++){
			List<XM_BM_XM_MC> bm_mc_list = new ArrayList<XM_BM_XM_MC>();
			//System.out.println(listlb.get(i).getLB_BM().trim());
			for(int j=0; j<list_sjgz.size(); j++){
				XM_BM_XM_MC bm_mc= new XM_BM_XM_MC();
				if((listlb.get(i).getLB_BM().trim()).equals(list_sjgz.get(j).getGZ_LB().trim())){
					
					bm_mc.setXM_BM(Utils.getXM_BM(list_sjgz.get(j).getXM_BM().trim()));
					
					bm_mc.setXM_MC(list_sjgz.get(j).getXM_MC().trim());
					
					//System.out.print(Utils.getXM_BM(list_sjgz.get(j).getXM_BM().trim()) + " | ");
	
					bm_mc_list.add(bm_mc);
				}
			}
			//System.out.println();
			map_bm_mc_list.put(listlb.get(i).getLB_BM().trim(), bm_mc_list);
		}
		
		CreateDWGZMXPDF_TOTAL c = new CreateDWGZMXPDF_TOTAL();
	    c.createPDF(map_bm_mc_list,listDWCOUNT,listlb,month);
	    System.out.println("制作完成");
	}
}
